﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class ButtonPointerHandler
{
    public static Dictionary<int, TouchPhase> touchs = new Dictionary<int, TouchPhase>();
    private PointerEventData data = null;
    private static int currentFrame = 0;

    public void SetData(PointerEventData pointerEventData)
    {
        data = pointerEventData;
    }

    public bool ContainsData()
    {
        return data != null;
    }

    public void ClearData()
    {
        data = null;
    }

    public PointerEventData GetData()
    {
        return data;
    }

    public bool IsUp()
    {
        if (Application.platform == RuntimePlatform.WindowsEditor || data == null) return false;
        if (currentFrame != Time.frameCount)
        {
            Reset();
            currentFrame = Time.frameCount;
        }
        if (touchs.ContainsKey(data.pointerId))
        {
            TouchPhase touch = touchs[data.pointerId];
            if (touch == TouchPhase.Ended || touch == TouchPhase.Canceled)
            {
                return true;
            }
            return false;
        }
        else
        {
            return true;
        }
    }

    private static void Reset()
    {
        touchs.Clear();
        for (int i = 0; i < Input.touchCount; i++)
        {
            touchs.Add(Input.GetTouch(i).fingerId, Input.GetTouch(i).phase);
        }
    }

    public static void Key(MonoBehaviour mono, KeyCode keyCode)
    {
        if (keyCode != KeyCode.None)
        {
            PointerEventData pointerData = new PointerEventData(EventSystem.current);
            if (Input.GetKeyDown(keyCode))
            {
                ExecuteEvents.Execute(mono.gameObject, pointerData, ExecuteEvents.pointerDownHandler);
            }
            else if (Input.GetKey(keyCode))
            {

            }
            else if (Input.GetKeyUp(keyCode))
            {
                ExecuteEvents.Execute(mono.gameObject, pointerData, ExecuteEvents.pointerUpHandler);
            }
        }
    }

}
